<?php
/**
 * Created by PhpStorm.
 * User: linyh
 */

namespace app\controllers;

use Yii;
use yii\base\Exception;
use yii\base\UserException;
use yii\helpers\Json;
use yii\web\HttpException;
use yii\web\Response;

class ErrorAction extends \yii\web\ErrorAction {
    public function run() {
        if (($exception = Yii::$app->errorHandler->exception) === null) {
            // action has been invoked not from error handler, but by direct route, so we display '404 Not Found'
            $exception = new HttpException(404, Yii::t('yii', 'Page not found.'));
        }

        if ($exception instanceof Exception) {
            $name = $exception->getName();
        } else {
            $name = $this->defaultName ?: Yii::t('yii', 'Error');
        }

        if ($exception instanceof UserException) {
            $message = $exception->getMessage();
        } else {
            $message = $this->defaultMessage ?: '服务器内部错误';
        }

        if (Yii::$app->getRequest()->getIsAjax()) {
            Yii::$app->response->statusCode = 200;
            Yii::$app->response->format = Response::FORMAT_JSON;
            return [
                'state' => 600,
                'message' => $message,
                'data' => [],
            ];
        } else {
            $exception->statusCode = 400;
            return $this->controller->render($this->view ?: $this->id, [
                'name' => $name,
                'message' => $message,
                'exception' => $exception,
            ]);
        }
    }
}
